package com.md.youyouhui.ui.login;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.md.youyouhui.R;
import com.md.youyouhui.databinding.FragmentMsgLoginBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.response.LoginResponse;
import com.md.youyouhui.ui.BaseFragment;
import com.md.youyouhui.ui.MainActivity;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by AdministratorZJ
 * on 2019/4/3.
 */
public class MsgLoginFragment extends BaseFragment {
    private FragmentMsgLoginBinding msgLoginBinding;
    private Timer timer = new Timer();
    private TimerTask timerTask;
    private int time = 60;
    private MainViewModel viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        msgLoginBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_msg_login, container, false);
        viewModel = new MainViewModel();
        initData1();
        return msgLoginBinding.getRoot();
    }

    private void initData1() {
        msgLoginBinding.loginBtn.setOnClickListener(v -> msgLogin());
        msgLoginBinding.userPass.setOnClickListener(v -> ((LoginActivity) mActivity).defaultLogin());
        msgLoginBinding.loginRegister.setOnClickListener(v -> {
            LoginFragment fragment = (LoginFragment) getActivity().getSupportFragmentManager().findFragmentByTag(LoginFragment.class.getSimpleName());
            fragment.forgetPass();
        });
        msgLoginBinding.timeCode.setOnClickListener(v -> sendCodeService());
    }

    private void sendCodeService() {
        String phone = msgLoginBinding.loginPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(mActivity, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        viewModel.sendCode(phone).observe(this, codeResponse -> {
            assert codeResponse != null;
            switch (codeResponse.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    sendCode();
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, codeResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void msgLogin() {
        String phone = msgLoginBinding.loginPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(mActivity, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        String code = msgLoginBinding.loginCode.getText().toString();
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(mActivity, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        //类型:1.验证码登录2.密码登录
        viewModel.login(1, phone, code, "", "android").observe(this, objectResource -> {
            assert objectResource != null;
            switch (objectResource.status) {
                case LOADING:
                    msgLoginBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    msgLoginBinding.progress.setVisibility(View.GONE);
                    LoginResponse data = objectResource.data;
                    if (null == data) {
                        return;
                    }
                    SharedPreferencesUtils.saveString(mActivity, Constants.USER_TOKEN, data.token);
                    SharedPreferencesUtils.saveString(mActivity, Constants.INVITED_CODE, data.invitedCode);
                    //((LoginActivity) mActivity).requestLogin();
                    startActivity(new Intent(mActivity, MainActivity.class));
                    if (null == getActivity()) {
                        return;
                    }
                    getActivity().finish();
                    break;
                case ERROR:
                    msgLoginBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(mActivity, objectResource.errorCode);
                    break;
                default:
                    msgLoginBinding.progress.setVisibility(View.GONE);
                    break;
            }
        });
    }

    private void sendCode() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                time--;
                mActivity.runOnUiThread(() -> {
                    msgLoginBinding.timeCode.setText(String.format("%dS", time));
                    if (time == 0) {
                        time = 60;
                        msgLoginBinding.timeCode.setText("发送验证码");
                        msgLoginBinding.timeCode.setEnabled(true);
                        timerTask.cancel();
                    } else {
                        msgLoginBinding.timeCode.setEnabled(false);
                    }
                });
            }
        };
        timer.schedule(timerTask, 100, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null == timer) {
            return;
        }
        if (null != timerTask) {
            timerTask.cancel();
        }
        timer.purge();
        timer.cancel();
    }

}
